// pages/user/index.js
import { request } from "../../request/request.js";
Page({
  data: {
    userinfo:{},
    // 被收藏的商品的数量
    collectNums:0
  },

  flag:false,

  onShow(){
    const userinfo=wx.getStorageSync("userinfo");
    
    if(userinfo != ""){
      const collect=wx.getStorageSync("collect")||[];
      if(!this.flag){
        wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey
        if(res.code){
          wx.request({
            url: 'https://api.weixin.qq.com/sns/jscode2session',//微信服务器获取appid的网址 不用变
            method:'post',//必须是post方法
            data:{
              js_code:res.code,
              appid:'wxc359642a8431832b',//仅为实例appid
              secret:'1a01394c2029a4f519c5082232864c73',//仅为实例secret
              grant_type:'authorization_code'
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded',
            },
            success:function(response){
              wx.setStorageSync('app_openid', response.data.openid); //将openid存入本地缓存
              wx.setStorageSync('sessionKey', response.data.session_key)//将session_key 存入本地缓存命名为SessionKey
            }
          })
        }else{
          console.log("登陆失败");
        }
      }
        });
        this.flag = true;
      }
      this.setData({userinfo,collectNums:collect.length})
    }

    ;
  },

  handleGetUserInfo(){
    const collect=wx.getStorageSync("collect")||[];
    const that = this;
    wx.getUserProfile({
     desc: '正在获取', //不写不弹提示框
     success: function (res) {
      request({ url: "/goods/goodsDetail"}).then(result=>{
        if(collect.length == 0){
          for(var index in result){
            if(result[index].isCollect == 1){
              collect.push(result[index]);
            }
            wx.setStorageSync('collect', collect)
          }
        }
        
      })
       const {userInfo} = res;
       wx.setStorageSync("userinfo", userInfo);
       that.setData({
         userinfo:userInfo,
         collectNums:collect.length})
     },
     fail: function (err) {
       console.log("获取失败: ", err)
     }
    });
  },

  handleDeleteUserInfo(){
    const that = this;
    wx.removeStorage({
      key: 'userinfo',
      success: function(res) {
        that.setData({
         userinfo:{},
         collectNums:0})
        console.log(res.data);
      }
    })
  },

  onLoad: function (options) {
    
  }


})